package com.example.demo.security.service.impl;

import com.example.demo.exception.LoginException;
import com.example.demo.security.entity.SysUser;
import com.example.demo.security.service.ILoginService;
import com.example.demo.security.support.LoginUser;
import com.example.demo.utils.JwtUtil;
import com.example.demo.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname LoginServiceImpl
 * @description
 * @date 2024/04/02 14:43
 * <p>
 * ******************************************************
 */
@Service("securityLoginService")
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;

    @Override
    public HashMap<String, String> login(SysUser user) {
        // authenticationManager authenticate验证
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        Authentication authenticate =
                authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new LoginException("用户名或密码错误");
        }
        //使用userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getSysUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);
        //authenticate存入redis
        redisCache.setCacheObject("login:" + userId, loginUser);
        //把token响应给前端
        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);
        return map;
    }

    @Override
    public void logout() {
        Authentication authentication =
                SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getSysUser().getId();
        redisCache.deleteObject("login:"+userid);
    }

}
